package com.hctforgreen.greenservice.model;

import android.content.Context;

import com.hctforgreen.greenservice.model.SerieListEntity.ChildSerieEntity;
import com.hctforgreen.greenservice.utils.HctConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * XXX 4、根据系列ID获取资料 由getAllBooks替代
 * 
 * @author Tallen Zhai
 * 
 */
public class BookListEntity extends BaseEntity {

	private static final long serialVersionUID = 425934856380145828L;

	public List<BookEntity> dataList = null;

	public List<MachineBooksEntity> machineBooksList = null;

	public List<ChildSerieEntity> childSeriesBooksList = null;

	public String statusCode = "";
	public String msg = "";
	public final static String STATUS_CODE = "statusCode";
	public final static String MSG = "msg";
	private final static String BOOKS = "books";

	private final static String MACHINE_BOOKS = "machineBooks";
	private final static String CHILD_SERIES_BOOKS = "childSeriesBooks";

	public static BookListEntity parse(JSONObject jsonObject)
			throws JSONException {
		BookListEntity bean = new BookListEntity();
		if (jsonObject.has(STATUS_CODE)) {
			bean.statusCode = jsonObject.getString(STATUS_CODE);
		}
		if (jsonObject.has(MSG)) {
			bean.msg = jsonObject.getString(MSG);
		}
		/**
		 * 解析books节点
		 */
		if (jsonObject.has(BOOKS)) {

			JSONArray jsonArray = jsonObject.getJSONArray(BOOKS);

			bean.dataList = new ArrayList<BookEntity>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				BookEntity entity = BookEntity.parse(object);
				bean.dataList.add(entity);
			}

		}

		/**
		 * 解析machineBooks节点
		 */
		if (jsonObject.has(MACHINE_BOOKS)) {

			JSONArray jsonArray = jsonObject.getJSONArray(MACHINE_BOOKS);

			bean.machineBooksList = new ArrayList<MachineBooksEntity>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				MachineBooksEntity entity = MachineBooksEntity.parse(object);
				bean.machineBooksList.add(entity);
			}

		}
		/**
		 * 解析childSeriesBooks节点
		 */
		if (jsonObject.has(CHILD_SERIES_BOOKS)) {

			JSONArray jsonArray = jsonObject.getJSONArray(CHILD_SERIES_BOOKS);

			bean.childSeriesBooksList = new ArrayList<ChildSerieEntity>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				ChildSerieEntity entity = ChildSerieEntity.parse(object);
				bean.childSeriesBooksList.add(entity);
			}

		}
		return bean;
	}

	public static class MachineBooksEntity extends BaseEntity {

		private static final long serialVersionUID = 6143893352271914696L;

		public String machineId = "";
		public ArrayList<String> machineBookIdList = new ArrayList<String>();
		public List<BookEntity> dataList = null;

		public final static String MACHINE_ID = "machineId";

		public final static String MACHINE_BOOK_ID_LIST = "machineBookIdList";

		public static MachineBooksEntity parse(JSONObject jsonObject)
				throws JSONException {
			MachineBooksEntity bean = new MachineBooksEntity();
			if (jsonObject.has(MACHINE_ID)) {
				bean.machineId = jsonObject.getString(MACHINE_ID);
			}
			/**
			 * 解析machineBookIdList节点
			 */
			if (jsonObject.has(MACHINE_BOOK_ID_LIST)) {

				JSONArray jsonArray = jsonObject
						.getJSONArray(MACHINE_BOOK_ID_LIST);

				bean.machineBookIdList = new ArrayList<String>();
				for (int i = 0; i < jsonArray.length(); i++) {
					String bookId = jsonArray.getString(i);
					bean.machineBookIdList.add(bookId);
				}

			}
			return bean;
		}
	}

	public static class BookEntity extends BaseEntity {

		private static final long serialVersionUID = 1047724853306222162L;
		public String booktypeId = "";
		public String id = "";
		public String bookName = "";
		public String versionCode = "";

		public String booktypeName = "";
		@Deprecated
		public String seriesId = "";
		public String bookFileSize = "";

		/**
		 * 子系列编码
		 */
		@Deprecated
		public String childSeriesId = "";
		/**
		 * 子系列名称
		 */
		@Deprecated
		public String childSeriesName = "";

		public String columnId = "";
		public String displayName = "";
		public String bookFileLongSize = "";

		public final static String BOOK_TYPE_ID = "booktypeId";
		public final static String ID = "id";
		public final static String BOOK_NAME = "bookName";
		public final static String VERSION_CODE = "versionCode";

		public final static String BOOK_TYPE_NAME = "booktypeName";

		@Deprecated
		public final static String SERIES_ID = "seriesId";
		public final static String BOOK_FILE_SIZE = "bookFileSize";
		@Deprecated
		public final static String CHILD_SERIES_ID = "childSeriesId";
		@Deprecated
		public final static String CHILD_SERIES_NAME = "childSeriesName";

		public final static String COLUMN_ID = "columnId";

		public final static String DISPLAY_NAME = "displayName";
		public final static String BOOK_FILE_LONG_SIZE = "bookFileLongSize";

		// =========页面中才用的到=========

		/**
		 * 网络下载路径
		 */
		public String download_url = "";
		/**
		 * 下载进度
		 */
		public int progress = 0;

		/**
		 * book zip的状态
		 */
		public String bookZipState = "";

		public boolean isSelected = false;
		/**
		 * 是否可以更新
		 */
		public String bCanUpdate = "";
		public int notificationId = -1;
		/**
		 * 用来区分点击的是“下载”还是“更新”
		 */
		public String doWhatClick = "";
		public String currentBookFileLongSize = "";
		public String currentBookId = "";

		public String clickCount = "-1";

		public String suffix = "zip";// 文件后缀 默认是zip

		/**
		 * 2016-12-14 390694 添加当前点击下载的书的Node位置
		 * 页面中才用到
		 */
		public int nodePosition = 0;
		public int getNodePosition() {
			return nodePosition;
		}

		public void setNodePosition(int nodePosition) {
			this.nodePosition = nodePosition;
		}

		public static BookEntity parse(JSONObject jsonObject)
				throws JSONException {
			BookEntity bean = new BookEntity();
			if (jsonObject.has(BOOK_TYPE_ID)) {
				bean.booktypeId = jsonObject.getString(BOOK_TYPE_ID);
			}
			if (jsonObject.has(ID)) {
				bean.id = jsonObject.getString(ID);

			}
			if (jsonObject.has(BOOK_NAME)) {
				bean.bookName = jsonObject.getString(BOOK_NAME);
				bean.download_url = buildDownloadUrl(bean.bookName);
			}

			if (jsonObject.has("suffix")) {
				bean.suffix = jsonObject.getString("suffix");
			}
			if (jsonObject.has(VERSION_CODE)) {
				bean.versionCode = jsonObject.getString(VERSION_CODE);
			}
			// ==============
			if (jsonObject.has(BOOK_TYPE_NAME)) {
				bean.booktypeName = jsonObject.getString(BOOK_TYPE_NAME);
			}
			if (jsonObject.has(SERIES_ID)) {
				bean.seriesId = jsonObject.getString(SERIES_ID);
			}
			if (jsonObject.has(BOOK_FILE_SIZE)) {
				bean.bookFileSize = jsonObject.getString(BOOK_FILE_SIZE);
			}

			if (jsonObject.has(CHILD_SERIES_ID)) {
				bean.childSeriesId = jsonObject.getString(CHILD_SERIES_ID);
			}
			if (jsonObject.has(CHILD_SERIES_NAME)) {
				bean.childSeriesName = jsonObject.getString(CHILD_SERIES_NAME);
			}
			if (jsonObject.has(COLUMN_ID)) {
				bean.columnId = jsonObject.getString(COLUMN_ID);
			}

			if (jsonObject.has(DISPLAY_NAME)) {
				bean.displayName = jsonObject.getString(DISPLAY_NAME);
			}
			if (jsonObject.has(BOOK_FILE_LONG_SIZE)) {
				bean.bookFileLongSize = jsonObject
						.getString(BOOK_FILE_LONG_SIZE);
			}
			return bean;
		}

		// =============
		private static final String TOESCAPE = "<>:\"|?*\\";

		public interface Format {
			int NONE = 0;
			int ZIP = 4;
			int DOC = 1;
			int PDF = 2;
			int PPT = 3;
			int XLS = 5;
			int XLSX = 6;
		}

		private static String buildDownloadUrl(String bookName) {

			return HctConstants.NET_URL + HctConstants.NET_SOURCE_MOBILE_PATH
					+ HctConstants.GET_BOOK_ZIP_STREAM_ACTION
					+ HctConstants.NET_BOOK_NAME_HEADER + bookName;
		}

		/**
		 * 用download_url换算成文件在SDCard的路径，如果Db中的状态不是“解析完成”则return null
		 * 
		 * @param book
		 * @param format
		 * @return
		 */
		public static String inDbCopyFileName(BookEntity book, int format, Context context) {
			if (!book.bookZipState.equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_DONE)) {
				return null;
			}
			return makeBookFileName(book.download_url, book.suffix, context);
		}

		/**
		 * 用download_url换算成文件在SDCard的路径，如果没有文件则return null
		 * 
		 * @param url
		 * @param suffix
		 * @return
		 */
		public static String localCopyFileName(String url, String suffix, Context context) {
			if (url == null || url.equals("")) {
				return null;
			}
			String fileName = makeBookFileName(url, suffix, context);
			if (fileName != null && new File(fileName).exists()) {
				return fileName;
			}
			return null;
		}

		/**
		 * 用download_url换算成文件在SDCard的路径，不判断是否已有文件
		 * 
		 * @param url
		 * @param suffix
		 * @return
		 */
		public static String makeBookFileName(String url, String suffix, Context context) {
			if (url == null || url.equals("")) {
				return null;
			}
			URI uri;
			try {
				uri = new URI(url);
			} catch (Throwable ex) {
				return null;
			}

			String host = uri.getHost();

			StringBuilder path = new StringBuilder(host);
			if (host.startsWith("www.")) {
				path.delete(0, 4);
			}
			path.insert(0, File.separator);

			path.insert(0, HctConstants.getBooksRootPath(context)
					+ HctConstants.BOOKS_CACHE_STORE_PATH);

			int index = path.length();
			path.append(uri.getPath());
			int nameIndex = index;
			while (index < path.length()) {
				char ch = path.charAt(index);
				if (TOESCAPE.indexOf(ch) != -1) {
					path.setCharAt(index, '_');
				}
				if (ch == '/') {
					if (index + 1 == path.length()) {
						path.deleteCharAt(index);
					} else {
						path.setCharAt(index, File.separatorChar);
						nameIndex = index + 1;
					}
				}
				++index;
			}

			String ext = "." + suffix;
			// switch (format) {
			// case Format.ZIP:
			// ext = ".zip";
			// break;
			// case Format.DOC:
			// ext = ".doc";
			// break;
			// }

			// if (ext == null) {
			// int j = path.indexOf(".", nameIndex); // using not lastIndexOf
			// // to preserve
			// // extensions like
			// // `.fb2.zip`
			// if (j != -1) {
			// suffix = path.substring(j);
			// path.delete(j, path.length());
			// } else {
			// return null;
			// }
			// } else
			if (path.length() > ext.length()
					&& path.substring(path.length() - ext.length()).equals(ext)) {
				path.delete(path.length() - ext.length(), path.length());
			}

			String query = uri.getQuery();
			if (query != null) {
				index = 0;
				while (index < query.length()) {
					int j = query.indexOf("&", index);
					if (j == -1) {
						j = query.length();
					}
					String param = query.substring(index, j);
					if (!param.startsWith("username=")
							&& !param.startsWith("password=")
							&& !param.endsWith("=")) {
						int k = path.length();
						path.append("_").append(param);
						while (k < path.length()) {
							char ch = path.charAt(k);
							if (TOESCAPE.indexOf(ch) != -1 || ch == '/') {
								path.setCharAt(k, '_');
							}
							++k;
						}
					}
					index = j + 1;
				}
			}
			return path.append(ext).toString(); 
		}
	}

}
